package com.cse.config;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;


import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SaxXML extends DefaultHandler {
	
	Logger logger = Logger.getLogger(SaxXML.class);

	
	/* 此方法有三个参数
    arg0是传回来的字符数组，其包含元素内容
    arg1和arg2分别是数组的开始位置和结束位置 */
	@Override
	//读取文件内容的
	public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
		// TODO Auto-generated method stub
		
		String content = new String(arg0, arg1, arg2);
		logger.info(content);
		super.characters(arg0, arg1, arg2);
		
	}

	@Override
	public void endDocument() throws SAXException {
		// TODO Auto-generated method stub
		System.out.println("解析文档结束");
		super.endDocument();
	}

	@Override
	public void endElement(String arg0, String arg1, String arg2)
			throws SAXException {
		// TODO Auto-generated method stub
		System.out.println("解析元素结束");
		super.endElement(arg0, arg1, arg2);
	}

	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		System.out.println("开始解析文档");
		super.startDocument();
	}

	@Override
	public void startElement(String arg0, String arg1, String arg2,
			Attributes arg3) throws SAXException {
		// TODO Auto-generated method stub
		logger.info("开始解析元素 " + arg2);
		if(arg2.equals("site") && arg3.getValue(0).equals("yixun")){
	    if (arg3 != null) {
	       for (int i = 0; i < arg3.getLength(); i++) {
	            // getQName()是获取属性名称，
	    	   logger.info(arg3.getQName(i) + "=\"" + arg3.getValue(i) + "\"");
	        }
	     }
		}
	    System.out.println(arg2 + ":");
		super.startElement(arg0, arg1, arg2, arg3);
	}
	
	public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException{
		// 1.实例化SAXParserFactory对象
		SAXParserFactory factory = SAXParserFactory.newInstance();
		// 2.创建解析器
		SAXParser parser = factory.newSAXParser();
		// 3.获取需要解析的文档，生成解析器,最后解析文档
		InputStream input = DomXML.class.getResourceAsStream("/property.xml");
		SaxXML dh = new SaxXML();
		parser.parse(input, dh);
	}

}
